//
//  EDSCustomRequest.m
//  DrivieSchoolStudents
//
//  Created by TangBin on 2019/5/29.
//  Copyright © 2019 班文政. All rights reserved.
//

#import "EDSCustomRequest.h"
#import "AE_Solar-Swift.h"

@implementation EDSCustomRequest

- (NSArray *)parseList:(NSArray *)data cls:(Class)cls
{
    NSMutableArray *addList = [NSMutableArray array];
    for (NSDictionary *dict in data)
    {
        if ([dict isKindOfClass:[NSString class]])
        {
            [addList addObject:dict];
        }
        else
        {
            id resData = [cls yy_modelWithJSON:dict];
            [addList addObject:resData];
        }
    }
    return addList.copy;
}

- (void)requestCompleteFilter
{
    id rst = self.responseObject;
    id result = nil;
    if ([rst isKindOfClass:[NSDictionary class]] && [rst allKeys].count == 1) {
        NSString *data = rst[@"data"];
        NSString *empStr = [AESCrypt AES128Decrypt:data key:[AEUserCommonInfo getAesKey]];
        NSData *jsonData = [empStr dataUsingEncoding:NSUTF8StringEncoding];
        result = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"empStr=%@", empStr);
//        debugLog(@"ddd");
    } else {
        result = rst;
    }
    
    
//    NSLog(@"suce reuls=%@", NSStringFromClass([result class]));
//    NSDictionary *dict = result;
    
    if ([result isKindOfClass:[NSDictionary class]])
    {
        EDSRespondDataEntity *respond = [EDSRespondDataEntity new];
        respond.code = [result[@"code"] integerValue];
        respond.msg = result[@"msg"];
        respond.data = result[@"data"];
                
        if (respond.code == 401) { // 当前登录已失效，请重新登录
            [AEUserCommonInfo logout]; //设置状态
//            [AEUserCommonInfo jumpLoginVC]; // 跳转到登录页面
        }
        
        // 没有登录，认证失败,无效或过期token
//        if (respond.result == 20001)
//        {
//            [EDSUtility removeObjectForKey:@"userInfo"];
//            [EDSUtility removeObjectForKey:@"accessToken"];
//        }
        
       
        
        
        if (self.rspClass)
        {
            if ([respond.data isKindOfClass:[NSDictionary class]])
            {
                id tmpData = respond.data;
                if ([tmpData isKindOfClass:[NSDictionary class]] && ((NSDictionary *)tmpData).allKeys.count == 1)
                {
//                    NSLog(@"count=%d", ((NSDictionary *)tmpData).allValues.count);
                    id tmpDataTwo =((NSDictionary *)tmpData).allValues.firstObject;
                    if ([tmpDataTwo isKindOfClass:[NSDictionary class]])
                    {
                        respond.data = [self.rspClass yy_modelWithJSON:tmpDataTwo];
                        if ([respond.data isKindOfClass:[WDBaseRspModel class]] && self.recordsRspClass) {
                            NSArray *records = ((WDBaseRspModel *)respond.data).list;
                            if (records) {
                                respond.data = [self parseList:records cls:self.recordsRspClass];
                            }
                        }
                    }
                    else if ([tmpDataTwo isKindOfClass:[NSArray class]])
                    {
                        respond.data = [self parseList:tmpDataTwo cls:self.rspClass];
                    }
                    else if ([tmpDataTwo isKindOfClass:[NSString class]])
                    {
                        respond.data = [self.rspClass yy_modelWithJSON:respond.data];
                    }
                }
                else
                {
                    if ([tmpData isKindOfClass:[NSDictionary class]] && ((NSDictionary *)tmpData).allKeys.count == 0)
                    {
                        respond.data = nil;
                    }
                    else
                    {
                        respond.data = [self.rspClass yy_modelWithJSON:respond.data];
                        if ([respond.data isKindOfClass:[WDBaseRspModel class]] && self.recordsRspClass) {
                            NSArray *records = ((WDBaseRspModel *)respond.data).list;
                            if (records) {
                                respond.data = [self parseList:records cls:self.recordsRspClass];
                            }
                        }
                    }
//                    NSLog(@"data.class=%@", NSStringFromClass([respond.data class]));
                }
            }
            else if ([respond.data isKindOfClass:[NSArray class]])
            {
                respond.data = [self parseList:respond.data cls:self.rspClass];
            }
        }
        self.responseModelObject = respond;
        
//        NSLog(@"tb-resond=%@", self.responseObject);
        
        
        
        // token失效处理
        
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            if (respond.code == 220 && [respond.msg isEqualToString:@"无效的token"])
//            {// 跳转到登录页面
//                [SVProgressHUD showInfoWithStatus:@"无效的token"];
//                ZHCustomUserInfoModel *userInfo = [EDSAppDelegateTool sharedInstance].userInfoModel;
//                userInfo.loginState = 0;
//                userInfo.token = @"";
//                [[EDSAppDelegateTool sharedInstance] saveUserInfo:userInfo];
//
//                [[NSNotificationCenter defaultCenter] postNotificationName:kUSER_LOGINOUT_SUC_NOTI object:nil];
//
//                [[EDSAppDelegateTool sharedInstance] updateRootVC];
//            }
//        });
        
        
    }
    
}

- (void)requestFailedFilter
{
    EDSRespondDataEntity *respond = [EDSRespondDataEntity new];
    respond.code = EDS_NETWORK_NETFFAILED;//[NSString stringWithFormat:@"%ld", EDS_NETWORK_NETFFAILED];
    respond.msg = @"网络太慢，请稍后再试！";
    respond.data = nil;
    self.responseModelObject = respond;
}

#pragma mark - override
- (TYZRequestMethod)requestMethod
{
    return TYZRequestMethodPOST;
}

- (TYZRequestSerializerType)requestSerializerType
{
    return TYZRequestSerializerTypeJSON;
}

/*
 var header = ["Content-Type": "application/json"]
 
 header["CONSTANT_CURRENT_LANGUAGE"] = AppCache.shared.object(for: APPUserDefault.self).userSelectLanguage?.header ?? "en"
 
 if APPUser.shared.isLogin {
     header[APPUser.shared.userInfo.type] = APPUser.shared.token
 }
 */

- (NSDictionary<NSString *,NSString *> *)requestHeaderFieldValueDictionary
{
//    ZHCustomUserInfoModel *userInfo = [[EDSAppDelegateTool sharedInstance] getUserInfo];
    NSMutableDictionary *headers = [NSMutableDictionary dictionary];
    headers[@"Content-Type"] = @"application/json";
    headers[@"encrypted"] = [AEUserCommonInfo getRsa];

    // 语言
    NSString *lang = [AEUserCommonInfo currentLanguage];
    headers[@"CONSTANT_CURRENT_LANGUAGE"] = lang;
    // 是否登录
    BOOL isLogin = [AEUserCommonInfo isLogin];
//    NSLog(@"isLogin=%d", isLogin);
    NSString *userTypeKey = [AEUserCommonInfo userTypeKey];
    NSString *token = [AEUserCommonInfo getToken];
    if (isLogin) {
        headers[userTypeKey] = token;
    }
        
    return headers;
}

@end
